
from main import db
from sqlalchemy.exc import InvalidRequestError
from main.utils import JSONHelper
from datetime import datetime
from sqlalchemy import or_, and_, func
from main.models import User

def insert(object):
    try:
        object.time = datetime.now()
        db.session.add(object)
        db.session.commit()
        return True
    except InvalidRequestError:
        db.session.rollback()
    except Exception as e:
        print(e)
        return False


def update(object):
    try:
        object.time = datetime.now()
        db.session.commit()
        return True
    except InvalidRequestError:
        db.session.rollback()
    except Exception as e:
        print(e)
        return False


def query_by_id(id):
    '''
    query user by id
    :param id:
    :return: user
    '''
    return User.query.filter(User.id == id).first()


def query_by_openid(openid):
    '''
    query user by openid
    :param openid:
    :return: user
    '''
    return User.query.filter(User.openid == openid).first()


if __name__ == '__main__':
    print(query_by_id(1).to_json())
